/*
 *  ajax请求
 *
 * @Author:    1024创新实验室-主任：卓大
 * @Date:      2022-09-06 20:46:03
 * @Wechat:    zhuda1024
 * @Email:     lab1024@163.com
 * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
 */
import { message } from 'ant-design-vue';
import axios from 'axios';
import { encryptData } from './encrypt';

import _ from 'lodash';



// 创建axios对象
const smartAxios = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL,
});


// ================================= 请求拦截器 =================================

smartAxios.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// ================================= 响应拦截器 =================================

// 添加响应拦截器
smartAxios.interceptors.response.use(
  (response) => {
    return Promise.resolve(response);
  },
  (error) => {
    // 对响应错误做点什么
    if (error.message.indexOf('timeout') !== -1) {
      message.destroy();
      message.error('网络超时');
    } else if (error.message === 'Network Error') {
      message.destroy();
      message.error('网络连接错误');
    } else if (error.message.indexOf('Request') !== -1) {
      message.destroy();
      message.error('网络发生错误');
    }
    return Promise.reject(error);
  }
);

// ================================= 对外提供请求方法：通用请求，get， post, 下载download等 =================================

/**
 * get请求
 */
export const getRequest = (url: string, params?: any, config?: any) => {
  return request({ url, method: 'get', params, ...config });
};

/**
 * 通用请求封装
 * @param config
 */
export const request = (config: any) => {
  return smartAxios.request(config);
};

/**
 * post请求
 */
export const postRequest = (url: string, data?: any, config?: any) => {
  console.log(url)
  return request({
    data,
    url,
    method: 'post',
    ...config,
  });
};

// ================================= 加密 =================================

/**
 * 加密请求参数的post请求
 */
export const postEncryptRequest = (url: string, data: any) => {
  return request({
    data: { encryptData: encryptData(data) },
    url,
    method: 'post',
  });
};

// ================================= 下载 =================================

export const postDownload = function (url: string, data?: any) {
  return request({
    method: 'post',
    url,
    data,
    responseType: 'blob',
  })
    .then((data) => {
      handleDownloadData(data);
      return data;
    })
    .catch((error) => {
      handleDownloadError(error);
      return Promise.reject(error);
    });
};

/**
 * 文件下载
 */
export const getDownload = function (url: string, params?: any) {
  return request({
    method: 'get',
    url,
    params,
    responseType: 'blob',
  })
    .then((data) => {
      handleDownloadData(data);
      return data;
    })
    .catch((error) => {
      handleDownloadError(error);
      return Promise.reject(error);
    });
};

function handleDownloadError(error: any) {
  if (error instanceof Blob) {
    const fileReader = new FileReader();
    fileReader.readAsText(error);
    fileReader.onload = () => {
      const msg = fileReader.result as string;
      const jsonMsg = JSON.parse(msg);
      message.destroy();
      message.error(jsonMsg.msg);
    };
  } else {
    message.destroy();
    message.error('网络发生错误', error);
  }
}

function handleDownloadData(response: any) {
  if (!response) {
    return;
  }

  // 获取返回类型
  let contentType = _.isUndefined(response.headers['content-type']) ? response.headers['Content-Type'] : response.headers['content-type'];

  // 构建下载数据
  let url = window.URL.createObjectURL(new Blob([response.data], { type: contentType }));
  let link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;

  // 触发点击下载
  let disposition = response.headers['content-disposition'] || response.headers['Content-Disposition'];
  let filename = 'download.xlsx';
  if (disposition) {
    // 优先解析 filename*=
    const filenameStarMatch = disposition.match(/filename\*=([^;]+)/i);
    if (filenameStarMatch) {
      filename = filenameStarMatch[1];
      if (filename.toLowerCase().startsWith("utf-8''")) {
        filename = filename.substr(7);
      }
      filename = decodeURIComponent(filename);
    } else {
      // 其次解析 filename=
      const filenameMatch = disposition.match(/filename=([^;]+)/i);
      if (filenameMatch) {
        filename = filenameMatch[1].replace(/['"]/g, '');
        // 兼容 ISO-8859-1 编码
        try {
          filename = decodeURIComponent(escape(filename));
          filename = decodeURIComponent(filename);
        } catch (e) { }
      }
    }
  }
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();

  // 下载完释放
  document.body.removeChild(link); // 下载完成移除元素
  window.URL.revokeObjectURL(url); // 释放掉blob对象
}
